﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model;
using BLL;
using Model.Sys;
using System.Data;
using Common;

namespace WebPortal.Controllers
{
    public class RoleController : BaseController
    {
        #region 构造角色

        #endregion

        #region List
        public ActionResult List()
        {
            return View();
        }

        public ActionResult GetList(FormCollection formCollection)
        {
            string Name = string.Empty;
            string status = string.Empty;
            int pageSize = 10;
            int pageIndex = 1;
            int totalCount = 0;
            string expIDs = string.Empty;
            if (!string.IsNullOrEmpty(this.Request.Params["Name"]))
            {
                Name = this.Request.Params["Name"];
            }
            if (!string.IsNullOrEmpty(this.Request.Params["Status"]))
            {
                status = this.Request.Params["Status"];
            }
            if (status.Equals("-1"))
                status = string.Empty;
            if (!string.IsNullOrEmpty(formCollection["rows"]))
            {
                int.TryParse(formCollection["rows"], out pageSize);
            }
            if (!string.IsNullOrEmpty(formCollection["page"]))
            {
                int.TryParse(formCollection["page"], out pageIndex);
            }
            if (!string.IsNullOrEmpty(this.Request.Params["ExpIDs"]))
            {
                expIDs = this.Request.Params["ExpIDs"];
            }
            string order = Request.Params["order"];
            string sort = Request.Params["sort"];
            if (string.IsNullOrEmpty(sort))
            {
                sort = "Name";
            }
            if (string.IsNullOrEmpty(order))
            {
                order = "asc";
            }
            LoginInfo loginInfos = base.loginInfo();
            //loginInfos.DBName = dbName;
            RoleBll roleBll = new RoleBll(loginInfos);
            var list = roleBll.GetList(Name, status, expIDs,
                sort, order.Equals("asc", StringComparison.CurrentCultureIgnoreCase)
                , pageIndex, pageSize, out totalCount);

            var jsonDict = new Dictionary<String, Object> { { "total", totalCount }, { "rows", list } };
            return Json(jsonDict);
        }

        public ActionResult DeleteRole(string roleID)
        {
            LoginInfo loginInfos = base.loginInfo();
            RoleBll roleBll = new RoleBll(loginInfos);
            try
            {
                if (roleID.ToLower() == "3b46ae04-0152-483a-8ec4-5fa35edfbff2")
                    return Json("删除错误！系统管理员组不可删除。");
                roleBll.Delete(roleID);
                return Json(1);
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }

        #endregion

        #region Edit
        public ActionResult Edit(string roleID)
        {
            RoleInfo roleInfo = null;
            LoginInfo loginInfos = base.loginInfo();
            RoleBll roleBll = new RoleBll(loginInfos);
            if (!string.IsNullOrEmpty(roleID))
            {
                roleInfo = roleBll.GetInfoById(roleID);
            }
            else
            {
                roleInfo = new RoleInfo();
            }
            var dbList = roleBll.GetAllDB();
            var roledbList = new List<RoleDBInfo>();
            if (!string.IsNullOrEmpty(roleID))
            {
                roledbList = roleBll.GetRoleDBByRoleID(roleID);
            }
            if (roleInfo == null)
                roleInfo = new RoleInfo();
            PrepareRoleModel(roleInfo, dbList, roledbList);
            return View(roleInfo);
        }
        /// <summary>
        /// 更新角色信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        public ActionResult Update(RoleInfo model, FormCollection form)
        {
            LoginInfo loginInfos = base.loginInfo();
            RoleBll roleBll = new RoleBll(loginInfos);
            bool includeRole = true;

            #region 参数检查
            if (!string.IsNullOrEmpty(form["includeRole" + model.Id]) && form["includeRole" + model.Id].Equals("false"))
            {
                includeRole = false;
            }
            if (includeRole == true && string.IsNullOrEmpty(model.Name))
            {
                return Json(new
                {
                    Success = false,
                    Message = "角色名称不能为空！"
                });
            }
            #endregion

            #region 更新数据

            var taskResult = 0;
            if (includeRole == true)
            {
                if (string.IsNullOrEmpty(model.Id))
                {
                    model.Id = Guid.NewGuid().ToString();
                    var _tempList = roleBll.GetByNameWithOutId(model.Name);
                    if (_tempList.Count > 0)
                    {
                        return Json(new
                        {
                            Success = false,
                            Message = "保存失败，角色名称重复！"
                        });
                    }
                    taskResult = roleBll.Insert(model);
                }
                else
                {
                    var _tempList = roleBll.GetByNameWithOutId(model.Name, model.Id);
                    if (_tempList.Count > 0)
                    {
                        return Json(new
                        {
                            Success = false,
                            Message = "保存失败，角色名称重复！"
                        });
                    }
                    taskResult = roleBll.Update(model);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(model.Id))
                {
                    taskResult = 1;
                }
            }
            #endregion

            #region 解析权限配置

            if (taskResult == 1)
            {
                var allSelectIds = form["selectdbitem"] != null ? form["selectdbitem"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x)).ToList() : new List<int>();
                var roledbList = roleBll.GetRoleDBByRoleID(model.Id);
                foreach (var configItem in roledbList)
                {
                    bool remove = !allSelectIds.Contains(configItem.DBId);
                    if (remove)
                        roleBll.DeleteRoleDB(configItem.RoleId, configItem.DBId);
                    else
                    {
                        // 重置配置
                        configItem.IsConnected = 0;
                        configItem.IsEnable = 0;
                        configItem.IsManagement = 0;
                        configItem.IsView = 0;

                        #region 循环，防止大小写
                        foreach (string formKey in form.AllKeys)
                        {
                            if (formKey.Equals(string.Format("isConnected{0}", configItem.DBId), StringComparison.InvariantCultureIgnoreCase))
                            {
                                int newValue = configItem.IsConnected;
                                if (int.TryParse(form[formKey], out newValue))
                                {
                                    configItem.IsConnected = newValue.Equals(1) ? 1 : 0;
                                }
                            }
                            else if (formKey.Equals(string.Format("isEnable{0}", configItem.DBId), StringComparison.InvariantCultureIgnoreCase))
                            {
                                int newValue = configItem.IsEnable;
                                if (int.TryParse(form[formKey], out newValue))
                                {
                                    configItem.IsEnable = newValue.Equals(1) ? 1 : 0;
                                }
                            }
                            else if (formKey.Equals(string.Format("isManagement{0}", configItem.DBId), StringComparison.InvariantCultureIgnoreCase))
                            {
                                int newValue = configItem.IsManagement;
                                if (int.TryParse(form[formKey], out newValue))
                                {
                                    configItem.IsManagement = newValue.Equals(1) ? 1 : 0;
                                }
                            }
                            else if (formKey.Equals(string.Format("isView{0}", configItem.DBId), StringComparison.InvariantCultureIgnoreCase))
                            {
                                int newValue = configItem.IsView;
                                if (int.TryParse(form[formKey], out newValue))
                                {
                                    configItem.IsView = newValue.Equals(1) ? 1 : 0;
                                }
                            }

                        }
                        #endregion
                        roleBll.UpdateRoleDB(configItem);
                    }
                }
                foreach (var dbId in allSelectIds)
                {
                    var _tempRoleDB = (from roledb in roledbList
                                       where roledb.DBId.Equals(dbId)
                                       select roledb).FirstOrDefault();
                    if (_tempRoleDB == null)
                    {
                        var configItem = new RoleDBInfo() { RoleId = model.Id, DBId = dbId };
                        #region 循环，防止大小写
                        foreach (string formKey in form.AllKeys)
                        {
                            if (formKey.Equals(string.Format("isConnected{0}", configItem.DBId), StringComparison.InvariantCultureIgnoreCase))
                            {
                                int newValue = configItem.IsConnected;
                                if (int.TryParse(form[formKey], out newValue))
                                {
                                    configItem.IsConnected = newValue.Equals(1) ? 1 : 0;
                                }
                            }
                            else if (formKey.Equals(string.Format("isEnable{0}", configItem.DBId), StringComparison.InvariantCultureIgnoreCase))
                            {
                                int newValue = configItem.IsEnable;
                                if (int.TryParse(form[formKey], out newValue))
                                {
                                    configItem.IsEnable = newValue.Equals(1) ? 1 : 0;
                                }
                            }
                            else if (formKey.Equals(string.Format("isManagement{0}", configItem.DBId), StringComparison.InvariantCultureIgnoreCase))
                            {
                                int newValue = configItem.IsManagement;
                                if (int.TryParse(form[formKey], out newValue))
                                {
                                    configItem.IsManagement = newValue.Equals(1) ? 1 : 0;
                                }
                            }
                            else if (formKey.Equals(string.Format("isView{0}", configItem.DBId), StringComparison.InvariantCultureIgnoreCase))
                            {
                                int newValue = configItem.IsView;
                                if (int.TryParse(form[formKey], out newValue))
                                {
                                    configItem.IsView = newValue.Equals(1) ? 1 : 0;
                                }
                            }
                        }
                        #endregion
                        roleBll.InsertRoleDB(configItem);
                        roledbList.Add(configItem);
                    }
                }
            }
            #endregion

            #region 输出结果
            if (taskResult == 1)
            {
                new SysOperationLog(loginInfos).Log("角色管理", Request.UserHostAddress, OperationAction.更新, OperationStatus.成功,
                      "更新角色操作,操作成功,ID=" + model.Id, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
                return Json(new
                {
                    Success = true,
                    Message = "保存成功"
                });
            }
            else
            {
                new SysOperationLog(loginInfos).Log("角色管理", Request.UserHostAddress, OperationAction.更新, OperationStatus.失败,
                        "更新角色操作,操作失败,ID=" + model.Id, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
                return Json(new
                {
                    Success = false,
                    Message = "保存失败"
                });
            }

            #endregion
        }

        [NonAction]
        protected void PrepareRoleModel(RoleInfo roleInfo, List<DBInfo> dbList, List<RoleDBInfo> roledbList)
        {
            if (roleInfo == null)
                throw new ArgumentNullException("cart");

            #region 属性
            //model.Id = roleInfo.Id;
            //model.Name = roleInfo.Name;
            //model.Description = roleInfo.Description;
            //model.RoleType = roleInfo.RoleType;
            //model.Status = roleInfo.Status;
            #endregion
            #region 数据库相关配置
            foreach (var dbItem in dbList)
            {
                var _tempRoleDB = (from roledb in roledbList
                                   where roledb.DBId.Equals(dbItem.Id)
                                   select roledb).FirstOrDefault();


                if (_tempRoleDB != null)
                {
                    //dbItemModel.IsConnected = _tempRoleDB.IsConnected.Equals(1);
                    //dbItemModel.IsEnable = _tempRoleDB.IsEnable.Equals(1);
                    //dbItemModel.IsManagement = _tempRoleDB.IsManagement.Equals(1);
                    //dbItemModel.IsView = _tempRoleDB.IsView.Equals(1);
                    _tempRoleDB.DBName = dbItem.DBName;
                    _tempRoleDB.DBDisplayName = dbItem.DisplayName;
                    _tempRoleDB.Selected = true;
                    roleInfo.RoleDBItems.Add(_tempRoleDB);
                }
                else
                {
                    var roledbInfo = new RoleDBInfo();
                    roledbInfo.DBId = dbItem.Id;
                    roledbInfo.DBName = dbItem.DBName;
                    roledbInfo.DBDisplayName = dbItem.DisplayName;
                    roleInfo.RoleDBItems.Add(roledbInfo);
                }
            }
            #endregion
        }

        #endregion

        #region DBConfig
        public ActionResult DBConfig(string roleID)
        {
            RoleInfo roleInfo = null;
            LoginInfo loginInfos = base.loginInfo();
            RoleBll roleBll = new RoleBll(loginInfos);
            if (!string.IsNullOrEmpty(roleID))
            {
                roleInfo = roleBll.GetInfoById(roleID);
            }
            else
            {
                roleInfo = new RoleInfo();
            }
            var dbList = roleBll.GetAllDB();
            var roledbList = new List<RoleDBInfo>();
            if (!string.IsNullOrEmpty(roleID))
            {
                roledbList = roleBll.GetRoleDBByRoleID(roleID);
            }
            if (roleInfo == null)
                roleInfo = new RoleInfo();
            PrepareRoleModel(roleInfo, dbList, roledbList);
            return View(roleInfo);
        }
        #endregion

        public ActionResult UserInRole(string roleID)
        {
            LoginInfo loginInfos = base.loginInfo();

            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            List<SysConfig> rows = bll.GetSysConfig("2");
            if (rows.Count > 0)
                return View(rows[0]);
            else
                return View(new SysConfig());
        }
        /// <summary>
        /// 更新组内用户状态
        /// </summary>
        /// <returns></returns>
        public ActionResult UpUserStatus()
        {
            LoginInfo loginInfos = base.loginInfo();
            string guid = Request.Params["guid"];
            string status = Request.Params["status"];
            RoleBll roleBll = new RoleBll(loginInfos);
            if (status == "1")
                status = "2";
            else
                status = "1";
            if (roleBll.UpUserStatus(guid, status))
                return Json("更新成功！");
            else
                return Json("更新失败！");
        }
        public ActionResult GetUserByRoleID(FormCollection formCollection)
        {
            string roleID = string.Empty;
            string username = string.Empty;
            string employeeName = string.Empty;
            int pageSize = 10;
            int pageIndex = 1;
            int totalCount = 0;
            string expIDs = string.Empty;
            Dictionary<String, Object> jsonDict = null;
            if (!string.IsNullOrEmpty(this.Request.Params["roleID"]))
            {
                roleID = this.Request.Params["roleID"];
            }
            else
            {
                jsonDict = new Dictionary<String, Object> { { "total", 0 }, { "rows", new { } } };
                return Json(jsonDict);
            }
            if (!string.IsNullOrEmpty(this.Request.Params["username"]))
            {
                username = this.Request.Params["username"];
            }
            if (!string.IsNullOrEmpty(this.Request.Params["employeeName"]))
            {
                employeeName = this.Request.Params["employeeName"];
            }

            if (!string.IsNullOrEmpty(formCollection["rows"]))
            {
                int.TryParse(formCollection["rows"], out pageSize);
            }
            if (!string.IsNullOrEmpty(formCollection["page"]))
            {
                int.TryParse(formCollection["page"], out pageIndex);
            }
            if (!string.IsNullOrEmpty(this.Request.Params["ExpIDs"]))
            {
                expIDs = this.Request.Params["ExpIDs"];
            }
            string order = Request.Params["order"];
            string sort = Request.Params["sort"];
            if (string.IsNullOrEmpty(sort))
            {
                sort = "Username";
            }
            if (string.IsNullOrEmpty(order))
            {
                order = "asc";
            }
            LoginInfo loginInfos = base.loginInfo();
            //loginInfos.DBName = dbName;
            RoleBll roleBll = new RoleBll(loginInfos);
            var list = roleBll.GetUserByRoleID(roleID, username, employeeName,
                sort, order.Equals("asc", StringComparison.CurrentCultureIgnoreCase)
                , pageIndex, pageSize, out totalCount);

            jsonDict = new Dictionary<String, Object> { { "total", totalCount }, { "rows", list } };
            return Json(jsonDict);
        }

        public ActionResult AddUserToRole(FormCollection formCollection)
        {
            #region 参数

            string roleID = string.Empty;
            string userIDs = string.Empty;
            string modelID = string.Empty;
            if (!string.IsNullOrEmpty(formCollection["roleID"]))
            {
                roleID = formCollection["roleID"];
            }
            if (!string.IsNullOrEmpty(formCollection["userIDs"]))
            {
                userIDs = formCollection["userIDs"];
            }
            if (!string.IsNullOrEmpty(formCollection["modelID"]))
            {
                modelID = formCollection["modelID"];
            }
            LoginInfo loginInfos = base.loginInfo();
            RoleBll roleBll = new RoleBll(loginInfos);
            RoleInfo roleInfo = null;
            #endregion

            #region 检查参数
            if (string.IsNullOrEmpty(roleID))
            {
                return Json(new { Success = false, Message = "角色不存在" });
            }
            if (string.IsNullOrEmpty(userIDs))
            {
                return Json(new { Success = false, Message = "没有提交的用户信息" });
            }
            roleInfo = roleBll.GetInfoById(roleID);
            if (roleInfo == null)
            {
                return Json(new { Success = false, Message = "角色不存在" });
            }
            var userIDArray = userIDs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            #endregion

            #region 更新数据
            ModelConfigBLL BLL = new ModelConfigBLL(loginInfos);
            DictionaryBLL bll = new DictionaryBLL(loginInfos);
            SysUserBLL userBll = new SysUserBLL();
            List<UserIFConfig> rows = bll.GetUserIFConfig();
            if (rows.Count == 0)
                return Json(new { Success = false, Message = "操作失败.请先配置人员接口配置！" });
            try
            {
                foreach (var userID in userIDArray)
                {
                    SysUserInfo userModel = SysUserBLL.GetInfoById(userID);
                    string userName = "";
                    string employeeName = "";
                    bool insertRole = false;
                    if (userModel == null)//从模型添加
                    {
                        DataTable modelDT = BLL.GetModelTbItem(userID, modelID);
                        userName = GetUserColumnValue(rows, modelDT, "Username");

                        if (userBll.CheckUserName(userName) == 1)
                        {
                            SysUserInfo model = new SysUserInfo();
                            model.Guid = Guid.NewGuid().ToString();
                            model.Username = userName;
                            model.EmployeeCode = GetUserColumnValue(rows, modelDT, "EmployeeCode");
                            model.EmployeeName = employeeName = GetUserColumnValue(rows, modelDT, "EmployeeName");
                            model.OfficeTel = GetUserColumnValue(rows, modelDT, "OfficeTel");
                            model.HomeTel = GetUserColumnValue(rows, modelDT, "HomeTel");
                            model.Mobile = GetUserColumnValue(rows, modelDT, "Mobile");
                            model.Gender = GetUserColumnValue(rows, modelDT, "Gender");
                            model.OfficeEmail = GetUserColumnValue(rows, modelDT, "OfficeEmail");
                            model.Pwd = GetUserColumnValue(rows, modelDT, "Pwd");
                            model.CreateUser = "";
                            model.CreateTime = DateTime.Now.ToString();
                            model.Status = 1;
                            model.CompanyName = GetUserColumnValue(rows, modelDT, "CompanyName");
                            model.Department = GetUserColumnValue(rows, modelDT, "Department");
                            model.Post = GetUserColumnValue(rows, modelDT, "Post");
                            model.UserType = 2;
                            userBll.Insert(model);//添加用户 
                            insertRole = true;
                        }
                    }
                    else//从本地添加
                    {
                        employeeName = userModel.EmployeeName;
                        userName = userModel.Username;
                        insertRole = true;
                    }
                    if (insertRole)
                    {
                        var roleUserInfo = new RoleUserInfo()
                        {
                            Guid = Guid.NewGuid().ToString(),
                            RoleID = roleID,
                            UserName = userName,
                            EmployeeName = employeeName,
                            CreateUser = loginInfos.UserName,
                        };
                        roleBll.InsertRoleUser(roleUserInfo);
                    }
                }
            }
            catch (Exception ex)
            {
                return Json(new { Success = false, Message = ex.Message });
            }
            #endregion
            return Json(new { Success = true, Message = "操作成功." });
        }
        public string GetUserColumnValue(List<UserIFConfig> rows, DataTable modelDT, string userColumnName)
        {
            try
            {
                UserIFConfig userIF = rows.Find(o => { return o.UserColumnName == userColumnName; });
                return modelDT.Rows[0][userIF.ModelColumnName].ToString();
            }
            catch
            {
                return "";
            }
        }
        public ActionResult RemoveUserFromRole(FormCollection formCollection)
        {
            #region 参数
            string guid = string.Empty;
            string roleID = string.Empty;
            string username = string.Empty;
            if (!string.IsNullOrEmpty(formCollection["guid"]))
            {
                guid = formCollection["guid"];
            }
            if (!string.IsNullOrEmpty(formCollection["roleID"]))
            {
                roleID = formCollection["roleID"];
            }
            if (!string.IsNullOrEmpty(formCollection["username"]))
            {
                username = formCollection["username"];
            }
            LoginInfo loginInfos = base.loginInfo();
            RoleBll roleBll = new RoleBll(loginInfos);
            RoleInfo roleInfo = null;
            #endregion

            #region 检查参数
            if (string.IsNullOrEmpty(guid))
            {
                return Json(new { Success = false, Message = "参数错误" });
            }
            #endregion


            #region 更新模型的推送名称
            var result = roleBll.DeleteRoleUser(guid);
            if (result == 1)
            {
                return Json(new { Success = true, Message = "删除成功" });
            }
            else
            {
                return Json(new { Success = false, Message = "删除失败" });
            }
            #endregion
        }


        public ActionResult Select()
        {
            return View();
        }


    }
}
